import 'dart:typed_data';
import 'dart:ui' as ui;
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_magic_planet/component/toast.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';

class ImageUtil {
  /// 检查相关系统权限
  static Future<void> checkPermission(Permission permission) async {
    var status = await permission.request();
    if (status.isDenied) {
      // 无权限的话就显示设置页面
      Toast.show('权限获取失败');
      return;
    }
  }

  static Future<ui.Image> capturePngToImage(GlobalKey key) async {
    RenderRepaintBoundary boundary =
        key.currentContext!.findRenderObject() as RenderRepaintBoundary;
    ui.Image image =
        await boundary.toImage(pixelRatio: window.devicePixelRatio);
    return image;
  }

  static Future<dynamic> saveImageToGallery(ui.Image uiImage) async {
    ByteData? byteData =
        await uiImage.toByteData(format: ui.ImageByteFormat.png);
    Uint8List picBytes = byteData!.buffer.asUint8List();
    final result = await ImageGallerySaver.saveImage(
      picBytes,
      quality: 100,
      name: DateTime.now().toString(),
    );
    print(result);
    return result;
  }
}
